using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using AXBC = Microsoft.Dynamics.BusinessConnectorNet;
using AXMD = Microsoft.Dynamics.Framework.Metadata.Ax;
using Proxy = Microsoft.Dynamics.Framework.BusinessConnector.Proxy;

namespace DynamicsAXPS
{
    [System.Management.Automation.Cmdlet("Create", "XPOForTable")]
    public class Create_XPOForTable : System.Management.Automation.PSCmdlet
    {
        [System.Management.Automation.Parameter(Position = 0, Mandatory = true)]
        public string Filename;

        [System.Management.Automation.Parameter(Mandatory = true)]
        public string Name;

        [System.Management.Automation.Parameter(Mandatory = true)]
        public string[] Fields;

        [System.Management.Automation.Parameter(Mandatory = true)]
        public string[] FieldTypes;
        
        protected override void ProcessRecord()
        {
            var w = new DynamicsAXUtil.XPOWriter(this.Filename);

            w.StartDocument();

            w.StartTable(Name);

            w.StartProperties();
            w.Property("Name", this.Name);
            w.EndProperties();

            w.StartFields();
            for (int i = 0; i < this.Fields.Length; i++)
            {
                string fieldname = this.Fields[i];
                w.StartField(fieldname, this.FieldTypes[i]);
                w.StartProperties();
                w.Property("Name", fieldname);
                w.Property("Table", this.Name);
                w.EndProperties();
                w.EndField();
            }
            w.EndFields();

            w.StartGroups();
            w.EndGroups();

            w.StartIndices();
            w.EndIndices();

            w.EndTable();
            w.EndDocument();

            w.Close();
        }
    }
}
